#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : gtmsAutoTestProject 
@File    : pos_device_save_server.py
@IDE     : PyCharm 
@Author  : Mario
@Date    : 2022/7/21 15:07 
@Describe: POS设备新建请求业务实现
"""
from Config.yamlRead import brandCode_cfg
from Comm.logUtils.logControl import LogHandler
from Comm.tools.toolsControl import ToolsHandler
from Comm.fakerUtils.fakerDataControl import fakerDataHandler
from FastApi.enum.Interface_enum.error_enum import ERROR_ENUM
from APIs.middleApi.setup.pos.pos_manage_api import PosManageAPI

CASH_CODE = "Auto_Generate"  # 机号名称
logger = LogHandler().get_logger()
faker = fakerDataHandler()


def get_random_name() -> str:
    """
    获取随机设备名称
    :return:
    """
    random_md5 = faker.get_random_md5()
    random_name = CASH_CODE + '_' + random_md5
    return random_name[0:20]


class PosDeviceSave:
    def __init__(self, environment):
        self.environment = environment
        self.middle_requests = PosManageAPI(environment)

    def get_device_brand(self) -> dict:
        """
        获取设备品牌字典
        :return:
        """
        device_brand_info = self.middle_requests.pos_device_manage_dicList_deviceBrand()
        device_brand_code = ToolsHandler.get_json_result(device_brand_info, "$.data[0]")
        logger.debug("获取设备品牌code[{}]成功~".format(device_brand_code))
        return device_brand_code

    def get_pos_printer_type(self) -> str:
        """
        获取打印机类型字典列表
        :return:
        """
        pos_printer_type_info = self.middle_requests.pos_printer_manage_printerTypeDic()
        printer_type_code = ToolsHandler.get_json_result(pos_printer_type_info, "$.data[0].code")
        logger.debug("获取打印机类型字典[{}]列表成功~".format(printer_type_code))
        return printer_type_code

    def pos_device_close(self, brandCode, deviceMac):
        """
        关闭其他品牌设备
        :param brandCode: 品牌编码
        :param deviceMac: 设备MAC
        :return:
        """
        brandCode_list = brandCode_cfg
        for i in brandCode_list:
            if i != brandCode:
                logger.debug("正在循环品牌[{}]的设备信息".format(i))
                device_info = self.middle_requests.pos_device_manage_page(i, deviceMac)  # 获取当前循环品牌设备信息
                device_status = ToolsHandler.get_json_result(device_info, '$..deviceStatus')  # 获取设备信息的设备状态
                logger.info("循环品牌的设备状态为:[{}]".format(device_status))
                if device_status == '1':
                    device_id = str(ToolsHandler.get_json_result(device_info, '$.data..id'))  # 获取需要关闭的设备ID
                    self.middle_requests.pos_derive_update_status(brandCode=i, deriveId=device_id, deviceStatus='0')
                    logger.info("正在关闭循环品牌[{}]的设备[{}]".format(i, device_id))
                    break

    def pos_device_save(self, brandCode, shopCode, deviceName, deviceMac, printerIp, deviceStatus, printerTypeCode, deviceBrandCode, deviceBrandName):
        """
        POS设备新建
        :param brandCode: 品牌编码
        :param shopCode: 门店编码
        :param deviceName: 设备名称(非必传参数，不传默认随机名称)
        :param deviceMac: 设备MAC,必传参数
        :param printerIp: 设备IP(非必传参数，不传默认随机IP)
        :param deviceStatus: 设备状态,非必传参数[0-禁用 1-启用]，不传默认禁用
        :param printerTypeCode: 打印机型号名称编码
        :param deviceBrandCode: 设备品牌编码
        :param deviceBrandName: 设备品牌名称
        :return:
        """
        device_info = self.middle_requests.pos_device_manage_page(brandCode, deviceMac)
        device_status = ToolsHandler.get_json_result(device_info, '$..deviceStatus')
        # 判断当前MAC是否有对应设备
        if device_status is None:  # 没有设备信息的情况才进行新建
            # 调用pos_device_close()方法关闭其他环境开启的设备
            self.pos_device_close(brandCode, deviceMac)
            result = self.middle_requests.pos_device_manage_save(
                brandCode=brandCode,
                shopCode=shopCode,
                deviceBrandCode=deviceBrandCode,
                deviceName=deviceName,
                deviceMac=deviceMac,
                printerIp=printerIp,
                deviceStatus=deviceStatus,
                cashCode=CASH_CODE,
                printerTypeCode=printerTypeCode,
                deviceBrandName=deviceBrandName
            )
            result_info = {"code": "200", "message": "设备[{}]新建成功,已为您打开该设备~".format(deviceName)}
            return result_info
        else:  # 有设备信息的话，返回一个错误信息
            result_info = {"code": ERROR_ENUM.DEVICE_TURNED_EXIST.value[0], "message": ERROR_ENUM.DEVICE_TURNED_EXIST.value[1]}
            return result_info

    def request_parameter_verification(self, brandCode, deviceName, deviceMac, printerIp, deviceStatus):
        """
        请求参数校验
        :param brandCode: 品牌编码
        :param deviceName: 设备名称(非必传参数，不传默认随机名称)
        :param deviceMac: 设备MAC,必传参数
        :param printerIp: 设备IP(非必传参数，不传默认随机IP)
        :param deviceStatus: 设备状态,非必传参数[0-禁用 1-启用]，不传默认禁用
        :return:
        """
        if deviceName is None:
            deviceName = get_random_name()
        if printerIp is None:
            printerIp = faker.get_random_ipv4()
        if deviceStatus is None:
            deviceStatus = '1'
        printerTypeCode = self.get_pos_printer_type()
        device_brand_dict = self.get_device_brand()
        deviceBrandCode = device_brand_dict['code']
        deviceBrandName = device_brand_dict['dataValue']
        shopCode = ToolsHandler.get_shopCode(brandCode)
        result = self.pos_device_save(brandCode, shopCode, deviceName, deviceMac, printerIp, deviceStatus, printerTypeCode, deviceBrandCode, deviceBrandName)
        return result


if __name__ == '__main__':
    test = PosDevicesave("sit")
    test.request_parameter_verification('823884', None, '24:69:8E:2B:5C:7E', None, None)
    test.request_parameter_verification('823884', None, '24:69:8E:2B:5C:7E', None, None)
